<template>
  <div class="permission-container">
    <div class="app-container">
      <el-card class="box-card">
        <PageTools style="text-align: right; margin-bottom: 20px">
          <template #right>
            <el-button type="primary" size="small" @click="addPermissionOne">新增权限</el-button>
          </template>
        </PageTools>
        <el-table border :data="list" row-key="id" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button v-if="row.type===1" size="small" type="text" @click="addPermissionTwo(row.id)">添加权限点</el-button>
              <el-button size="small" type="text" @click="editPermission(row.id)">编辑</el-button>
              <el-button size="small" type="text" @click="delPermission(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <addPermission :id="id" ref="son" :show-dialog.sync="showDialog" :title="title" />
    </div>
  </div>
</template>

<script>
import { getPermissionListApi, delPermissionApi, getDataApi } from '@/api/permission'
/**
 * 导入封装的平铺数据转树状方法
 */
import { scree } from '@/utils'
import addPermission from './components/addPermission.vue'
import { Message } from 'element-ui'
export default {
  name: 'Permission',
  components: {
    addPermission
  },
  data() {
    return {
      list: [],
      showDialog: false,
      title: '',
      id: ''
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    /**
     * 获取列表
     */
    async getPermissionList() {
      // 1.调用接口
      const { data } = await getPermissionListApi()
      // console.log(data)
      // 2.调用方法转换数据
      this.list = [...scree(data, '0')]
    },
    /**
     * 删除功能
     */
    delPermission(id) {
      // 1.温馨提示一下
      this.$confirm('此操作将永久删除该权限, 是否继续?', '温馨提示')
        .then(async() => {
          // 2.调用接口
          await delPermissionApi(id)
          // 3.提示删除
          Message.success('删除成功')
          // 4.从新获取数据
          this.getPermissionList()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 一级添加按钮
    addPermissionOne() {
      this.showDialog = true
      this.title = '新增权限-一级'
    },
    // 二级添加按钮
    addPermissionTwo(id) {
      this.id = id
      this.showDialog = true
      this.title = '新增权限-二级'
    },
    // 编辑功能
    async editPermission(id) {
      this.id = id
      this.showDialog = true
      this.title = '编辑权限'
      const { data } = await getDataApi(id)
      // console.log(data)
      // 回显数据
      this.$refs.son.form = data
    }
  }
}
</script>

<style lang='scss' scoped>

</style>
